﻿/* $RCSFile: CRMImageService.asmx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageManager/Services/CRMImageService.asmx.cs $
 * $log$
 * Revision 20 2010/08/10 17:55:42  christian.surieux
 *   Missing comments in asax asmx ashx files
 * Revision 7 2010/08/09 09:44:02  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Globalization;

using System.Web.UI;
using System.Web.UI.WebControls;

using AddonNice;
using AddonNice.Settings;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.CRMImage;
using AddonNice.Settings.CRMImage;
using AddonNice.CRMImage.UI.WebControls;

using Telerik.Web.UI;


namespace AddonNice.CRMImage
{
    /// <summary>
    /// Web services dealing with images
    /// </summary>
    [WebService(Namespace = "http://addonnice.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX. 
    [ScriptService]
    public class Service : WebService
    {
		/// <summary>
		/// Obtains PortalSettings from Current Context
		/// </summary>
        public PortalSettings portalSettings
		{
			get
			{
				if (HttpContext.Current != null)
					return (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
				return null;
			}
		}
        /*
        [WebMethod]
        public string GetToolTipData(object context)
	    {
            IDictionary<string, object> contextDictionary = (IDictionary<string, object>)context;
            string elementID = ((string)contextDictionary["Value"]);

            if (elementID == string.Empty)
            {
                throw new Exception("No Value argument is provided to the webservice!");
            }

            DataTable information = new DataTable();

		    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
            try
            {
                conn.Open();

			    SqlDataAdapter adapter = new SqlDataAdapter();

                try
                {
                    adapter.SelectCommand = new SqlCommand("SELECT * FROM [Customers] WHERE CustomerID=@id", conn);
                    adapter.SelectCommand.Parameters.AddWithValue("@id", elementID);
                    adapter.Fill(information);
                }
                finally
                {
                    if (!Object.Equals(adapter.SelectCommand, null)) adapter.SelectCommand.Dispose();
                }
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            DataRow row = information.Rows[0];
            
            return ViewManager.RenderView("~/Tooltip/Examples/WebService/CustomerInfo.ascx", information);      
        }
        */



        [WebMethod]
        public string GetFullSizeImage(object context)
        {
            IDictionary<string, object> contextDictionary = (IDictionary<string, object>)context;
            string imageID              = ((string)contextDictionary["Value"]);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetFullSizeImage BEG imageID: {0}.",imageID),CrmImageTrace.Sw.Info);

            if (imageID == string.Empty)
            {
                string msg  = "[E]CRMImageService GetFullSizeImage No Value argument is provided to the webservice!";
                if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine(msg,CrmImageTrace.Sw.Info);
                throw new Exception(msg);
            }
            Image img                   =   new Image();
            img.ImageUrl                =   imageID;
            img.Attributes["onload"]    =   "centerTooltip(this);this.onload = null;";
            StringWriter sw             =   new StringWriter();
            HtmlTextWriter writer       =   new HtmlTextWriter(sw);
            img.RenderControl(writer);
            writer.Flush();
            string result               =   sw.ToString();
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetFullSizeImage END result: {0}.",result),CrmImageTrace.Sw.Info);
            return result;
        }

        [WebMethod]
        public string GetThumbnailImage(object context)
        {
            IDictionary<string, object> contextDictionary = (IDictionary<string, object>)context;
            string imageID              = ((string)contextDictionary["Value"]);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetThumbnailImage BEG imageID: {0}.",imageID),CrmImageTrace.Sw.Info);

            if (imageID == string.Empty)
            {
                string msg  = "[E]CRMImageService GetThumbnailImage No Value argument is provided to the webservice!";
                if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine(msg,CrmImageTrace.Sw.Info);
                throw new Exception(msg);
            }
            Image img                   =   new Image();
            img.ImageUrl                =   imageID;
            img.Attributes["onload"]    =   "centerTooltip(this);this.onload = null;";
            StringWriter sw             =   new StringWriter();
            HtmlTextWriter writer       =   new HtmlTextWriter(sw);
            img.RenderControl(writer);
            writer.Flush();
            string result               =   sw.ToString();
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetThumbnailImage END result: {0}.",result),CrmImageTrace.Sw.Info);
            return result;
        }

        [WebMethod]
        public string GetDBFullSizeImage(object context)
        {
            IDictionary<string, object> contextDictionary = (IDictionary<string, object>)context;
            string imageIDstr           = ((string)contextDictionary["Value"]);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetDBFullSizeImage BEG imageID: {0}.",imageIDstr),CrmImageTrace.Sw.Info);
            
            if ( (imageIDstr == string.Empty) )
            {
                string msg  = "[E]CRMImageService GetDBFullSizeImage No Value argument is provided to the webservice!";
                if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine(msg,CrmImageTrace.Sw.Info);
                throw new Exception(msg);
            }
            SqlDataReader dr            =   null;
            CRMImageItem CRMImgItem     =   null;
            try
            {
                Guid    imageCrmId      =   new Guid(imageIDstr);
                dr                      =   GetImageFromDB(imageCrmId);
                DbEnumerator dbEnum     =   (DbEnumerator )dr.GetEnumerator();
                if (dbEnum.MoveNext())
                {
                    DbDataRecord di	    =   (DbDataRecord)dbEnum.Current;
                    CRMImgItem          =   new CRMImageItem();
                    string AlbumPath    =   portalSettings.CustomSettings[ImStr.AlbumPath].FullPath;
                    CRMImgItem.BindFromDB(di,AlbumPath,1,false,false,ImStr.adnimage,ImStr.adnimage,0,1,0,-1,string.Empty);
                }
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageService GetDBFullSizeImage ex: {0}.",ex),CrmImageTrace.Sw.Info);
                throw;
            }

            Image img                   =   new Image();
            img.ImageUrl                =   CRMImgItem.imageModifiedSrc;
            img.Attributes["onload"]    =   "centerTooltip(this);this.onload = null;";
            StringWriter sw             =   new StringWriter();
            HtmlTextWriter writer       =   new HtmlTextWriter(sw);
            img.RenderControl(writer);
            writer.Flush();
            string result               =   sw.ToString();
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetDBFullSizeImage END result: {0}.",result),CrmImageTrace.Sw.Info);
            return result;
        }
        /*
        [WebMethod]
        public string GetDBThumbnailImage(object context)
        {
            IDictionary<string, object> contextDictionary = (IDictionary<string, object>)context;
            string imageID              = ((string)contextDictionary["Value"]);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetThumbnailImage BEG imageID: {0}.",imageID),CrmImageTrace.Sw.Info);

            if (imageID == string.Empty)
            {
                string msg  = "[E]CRMImageService GetThumbnailImage No Value argument is provided to the webservice!";
                if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine(msg,CrmImageTrace.Sw.Info);
                throw new Exception(msg);
            }
            Image img                   =   new Image();
            img.ImageUrl                =   imageID;
            img.Attributes["onload"]    =   "centerTooltip(this);this.onload = null;";
            StringWriter sw             =   new StringWriter();
            HtmlTextWriter writer       =   new HtmlTextWriter(sw);
            img.RenderControl(writer);
            writer.Flush();
            string result               =   sw.ToString();
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageService GetThumbnailImage END result: {0}.",result),CrmImageTrace.Sw.Info);
            return result;
        }
         * */

        SqlDataReader GetImageFromDB(Guid imageCrmId)
        {
            return new CRMImageDB().GetCRMImageByEntityId(imageCrmId); 
        }

    }


    public class ViewManager
    {
        public static string RenderView(string path)
        {
            return RenderView(path,null, null);
        }

        public static string RenderView(string path, string propertyName, object data)
        {
            Page pageHolder = new Page();
            UserControl viewControl = (UserControl)pageHolder.LoadControl(path);

            if (data != null)
            {
                Type viewControlType = viewControl.GetType();
                FieldInfo field = viewControlType.GetField(propertyName);

                if (field != null)
                {
                    field.SetValue(viewControl, data);
                }
                else
                {
                    string msg  = string.Format("[E]ViewManager RenderView View file: {0} does not have a public '{1}' property",path,propertyName);
                    if ( CrmImageTrace.Sw.TraceError )
                        Trace.WriteLine(msg,CrmImageTrace.Sw.Info);
                    throw new Exception(msg);
                }
            }

            pageHolder.Controls.Add(viewControl);

            StringWriter output = new StringWriter();
            HttpContext.Current.Server.Execute(pageHolder, output, false);

            return output.ToString();
        }
    }

}
